#coding: utf-8
from time import sleep
import sys,serial,re
def check_com_is_ok(port):
    port = port 
    while True:
        try:
            ser = serial.Serial(port=port,baudrate=115200,timeout=1)
            print('open success')
            return ser
        except:
            print('open port '+port+' fail...')
            sleep(10)


def check_at_is_ok(com,match_str,timeout):
    out_str = ''
    count = 1
    while True:
        read_buf=com.read(300)
        out_str = out_str+read_buf
        if out_str.find(match_str) != -1:
            print out_str
            return True
        sleep(0.1)
        count = count+1
        if count>timeout*10:
            print out_str
            return False

def check_net_is_ok(com):
    read_buf = ''
    count = 1
    while True:
        com.write('AT+CGREG?\r\n')
        print 'AT+CGREG?'
        while True:
            out_str = com.read(300)
            read_buf = read_buf + out_str
            if read_buf:
                result = re.findall(r'\+CGREG: 0,([0-9])',read_buf)
                if result:
                    if int(result[0])==1:
                        print 'check_net_is_ok'
                        return True
                    else:
                        print read_buf
                        read_buf=''
                        sleep(5)
                else:
                    sleep(0.1)
                    count = count + 1
            if count > 3:
                print read_buf
                read_buf = ''
                count = 1
                sleep(5)
                break

        
